﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace DKT.WeiXinAPI.Factory
{
    /// <summary>
    /// 微信上下文对象
    /// </summary>
    public class WeiXinApiContext
    {
        /// <summary>
        /// 微信原始请求字符串
        /// </summary>
        public string RawMessage { get; set; }


        /// <summary>
        /// 微信原始请求XML
        /// </summary>
        public System.Xml.XmlDocument RawMessageXml { get; set; }

        /// <summary>
        /// 消息类型
        /// </summary>
        public string MessageType { get { return WeiXinParameters["MsgType"]; } }


        /// <summary>
        /// 微信发送的参数集
        /// </summary>
        public Dictionary<string, string> WeiXinParameters = new Dictionary<string, string>();


        /// <summary>
        /// 接收人
        /// </summary>
        public string ToUserName
        {
            get
            {
                return WeiXinParameters["ToUserName"];
            }
        }

        /// <summary>
        /// 发送人
        /// </summary>
        public string FromUserName
        {
            get
            {
                return WeiXinParameters["FromUserName"];
            }
        }

        public WeiXinApiContext()
        {

            RawMessage = ReadPost();
            System.Xml.XmlDocument xml_doc = new System.Xml.XmlDocument();
            xml_doc.LoadXml(RawMessage);


            if (xml_doc.ChildNodes.Count == 1)
            {
                var nodes = xml_doc.ChildNodes[0].ChildNodes;

                foreach (System.Xml.XmlNode node in nodes)
                {
                    if (!WeiXinParameters.ContainsKey(node.Name))
                    {
                        WeiXinParameters.Add(node.Name, node.InnerText);
                    }
                }
            }
        }


        private static string ReadPost()
        {
            Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            return Encoding.UTF8.GetString(b);
        }



    }
}
